//
//  JQFXHCalculationSuccessViewController.swift
//  jieqianfangxinhua
//
//  Created by 卢小艳 on 2025/8/22.
//

import Foundation
import UIKit
import SnapKit

class JQFXHCalculationSuccessViewController: HJYJBaseViewController {
    var total = 0.0
    var month = 0
    var type = 0
    var rate = 0.0
    var emiResult : (monthlyPayments: [Double], totalInterest: Double, totalAmount: Double)?
    
    init(total:Double, month: Int, backType: Int, rate: Double) {
        super.init(nibName: nil, bundle: nil)
        self.total = total
        self.month = month
        self.type = backType
        self.rate = rate
        
        let loanCalculator = JQFXHLoaneeCalculator(loanAmount: total, annualInterestRate: rate, loanTerm: month)
        
        if type == 0 {
            emiResult = loanCalculator.jqfxhCalculateeeEMI()
        }else if type == 1 {
            emiResult = loanCalculator.jqfxhCalculateEqualffPrincipal()
        }else {
            emiResult = loanCalculator.jqfxhCalculateInterestggFirst()
        }
        
        
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.jqfxhBigViewBgccGray
        self.jqfxhIsNavBarjjHidden = true
        self.view.addSubview(jqfxhTopBgxxImg)
        jqfxhTopBgxxImg.snp.makeConstraints { make in
            make.left.right.top.equalTo(self.view)
        }
        
        self.view.addSubview(jqfxhBackyyBtn)
        jqfxhBackyyBtn.snp.makeConstraints { make in
            make.left.equalTo(self.view).offset(20)
            make.top.equalTo(self.view).offset(UIApplication.shared.jqfxhSafeAreaInsets.top + 20)
            make.width.height.equalTo(30)
        }
        
        self.view.addSubview(jqfxhCalNavTitlebbLabel)
        jqfxhCalNavTitlebbLabel.snp.makeConstraints { make in
            make.centerY.equalTo(jqfxhBackyyBtn)
            make.centerX.equalTo(self.view)
        }
        
        self.view.addSubview(jqfxhContentkkView)
        
        jqfxhContentkkView.snp.makeConstraints { make in
            make.top.equalTo(self.jqfxhCalNavTitlebbLabel.snp.bottom).offset(23)
            make.left.equalTo(self.view).offset(16)
            make.right.equalTo(self.view).offset(-16)
            make.height.equalTo(234)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentTitleccLabel)
        jqfxhContentTitleccLabel.snp.makeConstraints { make in
            make.left.top.equalTo(jqfxhContentkkView).offset(12)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentJeddLabel)
        jqfxhContentJeddLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentTitleccLabel)
            make.top.equalTo(jqfxhContentTitleccLabel.snp.bottom).offset(12)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentJeeeCount)
        jqfxhContentJeeeCount.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentTitleccLabel)
            make.top.equalTo(jqfxhContentJeddLabel.snp.bottom).offset(3)
        }
        
        
        
        jqfxhContentkkView.addSubview(jqfxhContentQxffLabel)
        jqfxhContentQxffLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentkkView.snp.centerX).offset(10)
            make.top.equalTo(jqfxhContentJeddLabel)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentQxggCount)
        jqfxhContentQxggCount.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentQxffLabel)
            make.top.equalTo(jqfxhContentQxffLabel.snp.bottom).offset(3)
        }
        
        
        jqfxhContentkkView.addSubview(jqfxhContentNllhhLabel)
        jqfxhContentNllhhLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentJeddLabel)
            make.top.equalTo(jqfxhContentJeeeCount.snp.bottom).offset(14)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentNlliiCount)
        jqfxhContentNlliiCount.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentNllhhLabel)
            make.top.equalTo(jqfxhContentNllhhLabel.snp.bottom).offset(3)
        }
        
        
        
        jqfxhContentkkView.addSubview(jqfxhContentHkfsjjLabel)
        jqfxhContentHkfsjjLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentQxffLabel)
            make.top.equalTo(jqfxhContentNllhhLabel)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentHkfskkCount)
        jqfxhContentHkfskkCount.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentHkfsjjLabel)
            make.top.equalTo(jqfxhContentHkfsjjLabel.snp.bottom).offset(3)
        }
        
        jqfxhContentkkView.addSubview(jqfxhLineView)
        jqfxhLineView.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentJeddLabel)
            make.centerX.equalTo(jqfxhContentkkView)
            make.top.equalTo(jqfxhContentHkfskkCount.snp.bottom).offset(14)
            make.height.equalTo(1)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentYgjeLabel)
        jqfxhContentYgjeLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentJeddLabel)
            make.top.equalTo(jqfxhLineView.snp.bottom).offset(16)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentYgjeCount)
        jqfxhContentYgjeCount.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentYgjeLabel)
            make.top.equalTo(jqfxhContentYgjeLabel.snp.bottom).offset(3)
        }
        
        
        jqfxhContentkkView.addSubview(jqfxhContentZlxLabel)
        jqfxhContentZlxLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentYgjeLabel.snp.right).offset(46)
            make.top.equalTo(jqfxhContentYgjeLabel)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentZlxCount)
        jqfxhContentZlxCount.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentZlxLabel)
            make.top.equalTo(jqfxhContentZlxLabel.snp.bottom).offset(3)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentHkzeLabel)
        jqfxhContentHkzeLabel.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentZlxLabel.snp.right).offset(46)
            make.top.equalTo(jqfxhContentYgjeLabel)
        }
        
        jqfxhContentkkView.addSubview(jqfxhContentHkzeCount)
        jqfxhContentHkzeCount.snp.makeConstraints { make in
            make.left.equalTo(jqfxhContentHkzeLabel)
            make.top.equalTo(jqfxhContentHkzeLabel.snp.bottom).offset(3)
        }
        
        
        
        self.view.addSubview(jqfxhTipllView)
        
        jqfxhTipllView.snp.makeConstraints { make in
            make.top.equalTo(self.jqfxhContentkkView.snp.bottom).offset(18)
            make.left.right.equalTo(jqfxhContentkkView)
            make.height.equalTo(165)
        }
        
        
        jqfxhTipllView.addSubview(jqfxhTipTitleLabel)
        jqfxhTipTitleLabel.snp.makeConstraints { make in
            make.left.top.equalTo(jqfxhTipllView).offset(12)
        }
        
        for index in 0..<3 {
            let item = JQFXHCalResultTipItem(frame: CGRect(x: 0, y: 50 + index * 32, width: Int(jqfxhScreenWidth)-32, height: 32), index: index)
            jqfxhTipllView.addSubview(item)
        }

        
    }
    
    
    lazy var jqfxhTopBgxxImg : UIImageView = {
        let jqfxhTopBgxxImg = UIImageView(image: UIImage(named: "jqfxh_home_top"))
        jqfxhTopBgxxImg.isUserInteractionEnabled = true
        return jqfxhTopBgxxImg
    }()
    
    
    lazy var jqfxhContentkkView : UIView = {
        let jqfxhContentkkView = UIView()
        jqfxhContentkkView.backgroundColor = UIColor.white
        jqfxhContentkkView.layer.cornerRadius = 12
        jqfxhContentkkView.layer.masksToBounds = true
        return jqfxhContentkkView
    }()
    
    lazy var jqfxhTipllView : UIView = {
        let jqfxhTipllView = UIView()
        jqfxhTipllView.backgroundColor = UIColor.white
        jqfxhTipllView.layer.cornerRadius = 12
        jqfxhTipllView.layer.masksToBounds = true
        return jqfxhTipllView
    }()
    
    
    lazy var jqfxhBackyyBtn: UIButton = {
        let jqfxhBackyyBtn = UIButton(type: .custom)
        jqfxhBackyyBtn.setBackgroundImage(UIImage(named: "jqfxh_nav_white_back"), for: .normal)
        jqfxhBackyyBtn.addTarget(self, action: #selector(jqfxhBackyyBtnClick), for: .touchUpInside)
        return jqfxhBackyyBtn
    }()
    
    
    @objc func jqfxhBackyyBtnClick() {
        self.navigationController?.popViewController(animated: true)
    }
    
    
    lazy var jqfxhCalNavTitlebbLabel : UILabel = {
        let jqfxhCalNavTitlebbLabel = UILabel()
        jqfxhCalNavTitlebbLabel.font = UIFont.jqfxhRegular18
        jqfxhCalNavTitlebbLabel.textColor = UIColor.white
        jqfxhCalNavTitlebbLabel.text = "还款明细"
        return jqfxhCalNavTitlebbLabel
    }()
    
    
    lazy var jqfxhContentTitleccLabel : UILabel = {
        let jqfxhCalNavTitlebbLabel = UILabel()
        jqfxhCalNavTitlebbLabel.font = UIFont.jqfxhMedium16
        jqfxhCalNavTitlebbLabel.textColor = UIColor.black
        jqfxhCalNavTitlebbLabel.text = "贷款概要"
        return jqfxhCalNavTitlebbLabel
    }()
    
    lazy var jqfxhContentJeddLabel : UILabel = {
        let jqfxhContentJeddLabel = UILabel()
        jqfxhContentJeddLabel.font = UIFont.jqfxhRegular14
        jqfxhContentJeddLabel.textColor = UIColor(hex: "A6A6A6")
        jqfxhContentJeddLabel.text = "贷款金额"
        return jqfxhContentJeddLabel
    }()
    
    lazy var jqfxhContentJeeeCount : UILabel = {
        let jqfxhContentJeeeCount = UILabel()
        jqfxhContentJeeeCount.font = UIFont.jqfxhMedium14
        jqfxhContentJeeeCount.textColor = UIColor.black
        jqfxhContentJeeeCount.text = "￥" + String(self.total)
        return jqfxhContentJeeeCount
    }()
    
    lazy var jqfxhContentQxffLabel : UILabel = {
        let jqfxhContentQxffLabel = UILabel()
        jqfxhContentQxffLabel.font = UIFont.jqfxhRegular14
        jqfxhContentQxffLabel.textColor = UIColor(hex: "A6A6A6")
        jqfxhContentQxffLabel.text = "贷款期限"
        return jqfxhContentQxffLabel
    }()
    
    lazy var jqfxhContentQxggCount : UILabel = {
        let jqfxhContentQxggCount = UILabel()
        jqfxhContentQxggCount.font = UIFont.jqfxhMedium14
        jqfxhContentQxggCount.textColor = UIColor.black
        jqfxhContentQxggCount.text = String(self.month) + "期"
        return jqfxhContentQxggCount
    }()
    
    lazy var jqfxhContentNllhhLabel : UILabel = {
        let jqfxhContentNllhhLabel = UILabel()
        jqfxhContentNllhhLabel.font = UIFont.jqfxhRegular14
        jqfxhContentNllhhLabel.textColor = UIColor(hex: "A6A6A6")
        jqfxhContentNllhhLabel.text = "年利率"
        return jqfxhContentNllhhLabel
    }()
    
    lazy var jqfxhContentNlliiCount : UILabel = {
        let jqfxhContentNlliiCount = UILabel()
        jqfxhContentNlliiCount.font = UIFont.jqfxhMedium14
        jqfxhContentNlliiCount.textColor = UIColor.black
        jqfxhContentNlliiCount.text = String(self.rate) + "%"
        return jqfxhContentNlliiCount
    }()
    
    
    lazy var jqfxhContentHkfsjjLabel : UILabel = {
        let jqfxhContentHkfsjjLabel = UILabel()
        jqfxhContentHkfsjjLabel.font = UIFont.jqfxhRegular14
        jqfxhContentHkfsjjLabel.textColor = UIColor(hex: "A6A6A6")
        jqfxhContentHkfsjjLabel.text = "还款方式"
        return jqfxhContentHkfsjjLabel
    }()
    
    lazy var jqfxhContentHkfskkCount : UILabel = {
        let jqfxhContentHkfskkCount = UILabel()
        jqfxhContentHkfskkCount.font = UIFont.jqfxhMedium14
        jqfxhContentHkfskkCount.textColor = UIColor.black
        var type = "等额本息"
        if self.type == 1 {
            type = "等额本金"
        }else if self.type == 2 {
            type = "先息后本"
        }
        jqfxhContentHkfskkCount.text = type
        return jqfxhContentHkfskkCount
    }()
    
    
    lazy var jqfxhLineView : UIView = {
        let jqfxhLineView = UIView()
        jqfxhLineView.backgroundColor = UIColor(hex: "#E5E5E5")
        return jqfxhLineView
    }()
    
    
    lazy var jqfxhContentYgjeLabel : UILabel = {
        let jqfxhContentYgjeLabel = UILabel()
        jqfxhContentYgjeLabel.font = UIFont.jqfxhRegular14
        jqfxhContentYgjeLabel.textColor = UIColor(hex: "A6A6A6")
        jqfxhContentYgjeLabel.text = "月供金额"
        return jqfxhContentYgjeLabel
    }()
    
    lazy var jqfxhContentYgjeCount : UILabel = {
        let jqfxhContentYgjeCount = UILabel()
        jqfxhContentYgjeCount.font = UIFont.jqfxhMedium14
        jqfxhContentYgjeCount.textColor = UIColor.black
        jqfxhContentYgjeCount.text = String(format: "%.2f", emiResult?.monthlyPayments.first ?? 0)
        return jqfxhContentYgjeCount
    }()
    
    
    lazy var jqfxhContentZlxLabel : UILabel = {
        let jqfxhContentZlxLabel = UILabel()
        jqfxhContentZlxLabel.font = UIFont.jqfxhRegular14
        jqfxhContentZlxLabel.textColor = UIColor(hex: "A6A6A6")
        jqfxhContentZlxLabel.text = "总利息"
        return jqfxhContentZlxLabel
    }()
    
    lazy var jqfxhContentZlxCount : UILabel = {
        let jqfxhContentZlxCount = UILabel()
        jqfxhContentZlxCount.font = UIFont.jqfxhMedium14
        jqfxhContentZlxCount.textColor = UIColor.black
        jqfxhContentZlxCount.text = String(format: "%.2f",self.emiResult?.totalInterest ?? 0)
        return jqfxhContentZlxCount
    }()
    
    
    lazy var jqfxhContentHkzeLabel : UILabel = {
        let jqfxhContentHkzeLabel = UILabel()
        jqfxhContentHkzeLabel.font = UIFont.jqfxhRegular14
        jqfxhContentHkzeLabel.textColor = UIColor(hex: "A6A6A6")
        jqfxhContentHkzeLabel.text = "还款总额"
        return jqfxhContentHkzeLabel
    }()
    
    lazy var jqfxhContentHkzeCount : UILabel = {
        let jqfxhContentZlxCount = UILabel()
        jqfxhContentZlxCount.font = UIFont.jqfxhMedium14
        jqfxhContentZlxCount.textColor = UIColor.black
        jqfxhContentZlxCount.text = String(format: "%.2f",self.emiResult?.totalAmount ?? 0)
        return jqfxhContentZlxCount
    }()
    
    lazy var jqfxhTipTitleLabel : UILabel = {
        let jqfxhTipTitleLabel = UILabel()
        jqfxhTipTitleLabel.font = UIFont.jqfxhMedium16
        jqfxhTipTitleLabel.textColor = UIColor.black
        jqfxhTipTitleLabel.text = "还款小贴士"
        return jqfxhTipTitleLabel
    }()
    
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


class JQFXHCalResultTipItem: UIView {
    let titles = ["建议设置自动还款，避免逾期影响信用记录","提前还款可能会有违约金，具体请咨询贷款机构","保持良好还款记录有助于提升信用评分"]
    
    
    init(frame: CGRect, index: Int) {
        super.init(frame: frame)
        self.addSubview(jqfxhCalTipImg)
        jqfxhCalTipImg.snp.makeConstraints { make in
            make.centerY.equalTo(self)
            make.left.equalTo(self).offset(10)
            make.width.height.equalTo(16)
        }
        
        self.addSubview(jqfxhCalTipImgTitle)
        jqfxhCalTipImgTitle.snp.makeConstraints { make in
            make.centerY.equalTo(self)
            make.left.equalTo(jqfxhCalTipImg.snp.right).offset(2)
        }
        
        jqfxhCalTipImgTitle.text = titles[index]
        
    }
    
    
    lazy var jqfxhCalTipImg : UIImageView = {
        let jqfxhCalTipImg = UIImageView(image: UIImage(named: "jqfxh_caltip_icon"))
        jqfxhCalTipImg.isUserInteractionEnabled = true
        return jqfxhCalTipImg
    }()
    
    
    lazy var jqfxhCalTipImgTitle : UILabel = {
        let jqfxhCalTipImgTitle = UILabel()
        jqfxhCalTipImgTitle.font = UIFont.jqfxhRegular14
        jqfxhCalTipImgTitle.textColor = UIColor.black
        return jqfxhCalTipImgTitle
    }()
    
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}



struct JQFXHLoaneeCalculator {
    
    var loanAmount: Double  // 贷款金额
    var annualInterestRate: Double  // 年利率（百分比）
    var loanTerm: Int  // 贷款期数（个月）
    
    // 计算等额本息
    func jqfxhCalculateeeEMI() -> (monthlyPayments: [Double], totalInterest: Double, totalAmount: Double) {
        let monthlyInterestRate = (annualInterestRate / 100) / 12
        let monthlyPayment = loanAmount * monthlyInterestRate * pow(1 + monthlyInterestRate, Double(loanTerm)) / (pow(1 + monthlyInterestRate, Double(loanTerm)) - 1)
        
        var totalInterest: Double = 0
        var totalAmount: Double = 0

        
        var remainingLoan = loanAmount
        var monthlyPayments: [Double] = []

        for _ in 0..<loanTerm {
            let interestPayment = remainingLoan * monthlyInterestRate
            let principalPayment = monthlyPayment - interestPayment
            remainingLoan -= principalPayment
            
            totalInterest += interestPayment
            totalAmount += monthlyPayment
            
            monthlyPayments.append(monthlyPayment)
        }
        
        return (monthlyPayments, totalInterest, totalAmount)
    }
    
    // 计算等额本金
    func jqfxhCalculateEqualffPrincipal() -> (monthlyPayments: [Double], totalInterest: Double, totalAmount: Double) {
        let monthlyInterestRate = (annualInterestRate / 100) / 12
        let monthlyPrincipalPayment = loanAmount / Double(loanTerm)
        
        var monthlyPayments: [Double] = []
        var totalInterest: Double = 0
        var totalAmount: Double = 0
        var remainingLoan = loanAmount
        var monthlyInterests: [Double] = []

        for _ in 0..<loanTerm {
            let interestPayment = remainingLoan * monthlyInterestRate
            let monthlyPayment = monthlyPrincipalPayment + interestPayment
            remainingLoan -= monthlyPrincipalPayment
            
            totalInterest += interestPayment
            totalAmount += monthlyPayment
            
            monthlyPayments.append(monthlyPayment)
            monthlyInterests.append(interestPayment)
        }
        
        return (monthlyPayments, totalInterest, totalAmount)
    }
    
    // 计算先息后本
    func jqfxhCalculateInterestggFirst() -> (monthlyPayments: [Double], totalInterest: Double, totalAmount: Double) {
        let monthlyInterestRate = (annualInterestRate / 100) / 12
        let monthlyInterest = loanAmount * monthlyInterestRate
        let totalInterest = monthlyInterest * Double(loanTerm)
        let totalAmount = loanAmount + totalInterest
        
        var monthlyPayments: [Double] = []
        var monthlyPrincipal: [Double] = []
        var monthlyInterests: [Double] = []

        // 前期先付利息
        for _ in 0..<loanTerm - 1 {
            monthlyPayments.append(monthlyInterest)
            monthlyPrincipal.append(0.0)
            monthlyInterests.append(monthlyInterest)
        }
        
        // 最后一个月付本金+利息
        monthlyPayments.append(loanAmount + monthlyInterest)
        monthlyPrincipal.append(loanAmount)
        monthlyInterests.append(monthlyInterest)
        return (monthlyPayments, totalInterest, totalAmount)
    }
}
